<template>
  <div class="app-container">
    <el-form ref="form" :rules="rules" :model="addListForm" label-width="100px">
      <el-col :span="8">
        <el-form-item prop="strUsername" label="节目单名称">
          <el-input
            v-model="addListForm.strUsername"
            placeholder="请输入节目单名称"
            style="max-width: 220px"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="iOrgsysnum" label="所属机构">
          <!--prop 之前是strUsername-->
          <el-cascader
            v-model="addListForm.iOrgsysnum"
            :show-all-levels="false"
            :options="optionslist"
            :props="{ checkStrictly: true, expandTrigger: 'hover', value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="iUrgent" label="节目单类型">
          <el-select v-model="addListForm.iUrgent" placeholder="请选择">
            <el-option label="紧急" value="1"/>
            <el-option label="普通" value="0"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="strStartdate" label="生效日期">
          <el-date-picker
            v-model="addListForm.strStartdate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择生效日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="strEnddate" label="截至日期">
          <el-date-picker
            v-model="addListForm.strEnddate"
            style="width: 200px"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择截至日期"
            :picker-options="pickerOptionss"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="addListForm.iUrgent==='1'" :span="8">
        <el-form-item prop="iDevicesysnumArr" label="设备列表">
          <el-cascader
            v-model="addListForm.iDevicesysnumArr"
            style="width: 200px"
            :show-all-levels="false"
            :options="optionss"
            :props="{ multiple: true, checkStrictly: true,expandTrigger: 'hover', value:'iDevicesysnum',label:'strDevicename'}"

            @focus="devicefocus"
          />
        </el-form-item>
      </el-col>
      <!--<el-col :span="8">
        <el-form-item prop="iFrequency" label="播放次数">
          <el-select v-model="addListForm.iFrequency" placeholder="请选择播放次数">
            <el-option label="一次" value="1"></el-option>
            <el-option label="二次" value="2"></el-option>
            <el-option label="循环" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-col>-->

      <el-col :span="24">
        <el-form-item prop="strCycle" label="播放周期">
          <el-checkbox-group v-model="addListForm.strCycle">
            <el-checkbox
              v-for="(item, index) in playPeriod"
              :key="index"
              :label="item"
              @change="checkinlist"
            >{{ item }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="startTime" label="播放时间段">
          <!--<el-time-select
            placeholder="起始时间"
            v-model="addListForm.strCycleStartdata"
            :picker-options="{
            start: '08:00',
            step: '02:00',
            end: '18:00'
          }">
          </el-time-select>
          <el-time-select
            placeholder="结束时间"
            v-model="addListForm.strCycleEnddata"
            :picker-options="{
            start: '08:00',
            step: '02:00',
            end: '18:00',
            minTime: addListForm.strCycleStartdata
          }">
          </el-time-select>-->
          上午:
          <el-time-select
            v-model="addListForm.strCycleStartdata"
            placeholder="起始时间"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '12:00'
            }"
          />
          <el-time-select
            v-model="addListForm.strCycleEnddata"
            placeholder="结束时间"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '12:00',
              minTime: addListForm.strCycleStartdata
            }"
          />
          下午:
          <el-time-select
            v-model="addListForm.strCycleStarttime"
            placeholder="起始时间"
            :picker-options="{
              start: '12:00',
              step: '00:30',
              end: '24:00'
            }"
          />
          <el-time-select
            v-model="addListForm.strCycleEndtime"
            placeholder="结束时间"
            :picker-options="{
              start: '12:00',
              step: '00:30',
              end: '24:00',
              minTime: addListForm.strCycleStarttime
            }"
          />
        </el-form-item>
      </el-col>

      <div class="filter-container">
        <h3 style="color:#fff">素材选择</h3>
        <div class="filter-container">
          <el-button type="primary" @click="addMaterial()">添加素材</el-button>
        </div>
        <el-table
          ref="multipleTable"
          :data="materialData"
          row-key="id"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
        >
          <!--<el-table-column type="selection" >
            <el-checkbox :indeterminate="isIndeterminate" @change="handleCheckAllChange" v-model="checkAll"></el-checkbox>
          </el-table-column>-->
          <el-table-column type="selection" width="55" align="center"/>
          <!--<el-table-column type="index" width="55" label="序号" align="center"/>-->
          <el-table-column prop="strMaterialname" label="标题" align="center"/>
          <el-table-column prop="typeName" label="格式" align="center"/>
          <el-table-column prop="strOrgname" label="所属机构" align="center"/>
          <el-table-column label="下载地址" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <a :href="'http://'+scope.row.strDownload" target="_blank">{{ scope.row.strDownload }}</a>
            </template>
          </el-table-column>
          <el-table-column prop="time" label="排序" width="80" align="center">
            <template slot-scope="{row}">
              <el-input v-model="row.iOrder"/>
            </template>
          </el-table-column>
          <el-table-column label="播放次数" width="80" align="center">
            <template slot-scope="{row}">
              <el-input v-model="row.iPlaytime"/>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="240">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click.native.prevent="deleteRow(scope.$index, materialData)"
              >移除
              </el-button>
              <!--<el-button
                size="mini"
                type="primary"
                @click="replaceMaterial(scope.row,scope.$index)"
              >替换</el-button>-->
            </template>
          </el-table-column>
        </el-table>
        <span v-if="showspan" class="showspan">请勾选后提交</span>
      </div>
    </el-form>
    <el-button type="primary" style="position: absolute;right: 21px;" @click="publishPrograms('form')">保存</el-button>

    <el-dialog title="新增素材" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <div class="container">
        <el-form :model="addForm" label-width="80px">
          <el-col :span="8">
            <el-form-item label="所属机构" label-width="80px" :required="true">
              <el-cascader
                v-model="addForm.iOrgsysnum"
                :show-all-levels="false"
                :options="options"
                :props="{ checkStrictly: true, value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="strMaterialdetail" label="素材标签">
              <el-select v-model="addForm.strMaterialdetail" placeholder="请选择素材标签">
                <el-option
                  v-for="item in optionTag"
                  :key="item.id"
                  :label="item.strValue"
                  :value="item.strCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="searbtn">
            <el-form-item>
              <el-button type="primary" @click="addsearch()">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-form>
        <el-table ref="multipleaddTable" :data="addTableData" style="width: 100%" height="380" border
                  @selection-change="changeFun">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column type="index" width="55" label="序号" align="center"/>
          <el-table-column prop="strMaterialname" label="标题" align="center"/>
          <el-table-column prop="typeName" label="格式" align="center"/>
          <el-table-column prop="strMaterialdetailName" label="类型" align="center"/>
          <el-table-column prop="strCreatetime" label="创建时间" align="center"/>
          <el-table-column label="预览" align="center">
            <template slot-scope="scope">
              <a v-if="scope.row.iType===1">
                <el-image
                  style="width: 65px;height: 55px;border-radius: 10px"
                  :src="scope.row.strDownload"
                  :preview-src-list="[scope.row.strDownload]"
                />
              </a>
              <a v-else :href="'http://'+scope.row.strDownload" target="_blank">{{ scope.row.strDownload }}</a>
            </template>
          </el-table-column>
          <!--<el-table-column prop="type" label="操作" align="center">
            <template slot-scope="{row,$index}">
              <el-button size="mini" type="primary" @click="handaddsearch(row,$index)">详情</el-button>
            </template>
          </el-table-column>-->
        </el-table>
      </div>
      <div slot="footer">
        <el-button @click="clearsearch">取 消</el-button>
        <el-button type="primary" @click="addsearchture(),dialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getOrglist,
    addPrograms,
    getSysType,
    addsearchPrograms,
    getDevice, getOrglists
    // fabuPrograms
  } from '../../api/addTag'
  import { mapGetters } from 'vuex'
  // import Sortable from 'sortablejs'

  export default {
    name: 'AddProgramme',
    data() {

      var comparetdata1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择日期'))
        }
        // 转时间戳
        let timestr1 = this.addListForm.strStartdate    // 获取开始时间
        let timestr2 = this.addListForm.strEnddate      // 获取结束时间
        let time1 = new Date(timestr1).getTime()        // 开始时间转时间戳
        let time2 = new Date(timestr2).getTime()        // 结束时间转时间戳
        if (time1 > time2) {                            // 开始结束时间戳对比
          callback(new Error('生效日期不能大于截至日期'))
        } else {
          callback()
        }
      }
      var comparetdata2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择日期'))
        }
        // 转时间戳
        let timestr1 = this.addListForm.strStartdate
        let timestr2 = this.addListForm.strEnddate
        let time1 = new Date(timestr1).getTime()
        let time2 = new Date(timestr2).getTime()

        if (time1 > time2) {
          callback(new Error('截至日期不能小于生效日期'))
        } else {
          callback()
        }
      }
      return {
        // < 是选择今天及之后的时间，后面的-8.64e7就是可以选择今天和今天之后的。-8.64e6今天不可选
        // > 是选择今天以及今天之前的时间，后面的-8.64e6就是可以选择今天和今天之前的。
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pickerOptionss: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        // 校验
        rules: {
          strUsername: [
            { required: true, message: '请输入节目单名称', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
          iOrgsysnum: [
            { required: true, message: '请选择所属机构', trigger: 'change' }
          ],
          iUrgent: [
            { required: true, message: '请选择节目单类型', trigger: 'change' }
          ],
          strStartdate: [
            /* { required: true, message: '请选择日期', validator: comparetdata, trigger: 'change' }*/
            { required: true, validator: comparetdata1, trigger: 'change' }
          ],
          strEnddate: [
            /* { required: true, message: '请选择日期', trigger: 'change' }*/
            { required: true, validator: comparetdata2, trigger: 'change' }
          ],
          iPlaytime: [
            { required: true, message: '请选择播放次数', trigger: 'change' }
          ],
          strCycle: [
            {
              type: 'array',
              required: true,
              message: '请至少选择一个播放周期',
              trigger: 'change'
            }
          ],
          iDevicesysnumArr: [
            {
              type: 'array',
              required: true,
              message: '请选择列表',
              trigger: 'change'
            }
          ]
        },
        showspan: false,
        playPeriod: [
          '星期日',
          '星期一',
          '星期二',
          '星期三',
          '星期四',
          '星期五',
          '星期六'
        ],
        shebeiList: [],
        // checkPeriod: [],
        dialogVisible: false,
        checkAll: false,
        optionTag: [],
        materialData: [],
        multipleSelection: [],
        sortable: null,
        addForm: {
          iOrgsysnum: '',
          strMaterialdetail: '',
          iFlag: 1
        },
        options: [],
        optionss: [],
        strCycle: [],
        addTableData: [],
        optionslist:[],
        iOrgnum: this.$store.getters.iOrgsysnum,
        addListForm: {
          strUsername: '',
          iUrgent: '',
          strStartdate: '',
          strEnddate: '',
          strCycle: [],
          //strOperator: 'admin',
          // valArr: [],
          deviceType: 1,
          materialList: [],
          iFrequency: 1,
          iPlaytime: '',
          iOrder: '',
          iOrgsysnum: [],
          strCycleStartdata: '', // 中午开始时间
          strCycleEnddata: '', // 中午结束时间
          strCycleStarttime: '', // 下午开始时间
          strCycleEndtime: '', // 下午结束时间
          iDevicesysnumArr: [],
          iFlag: 1,
          strOperator:this.$store.getters.userID
        }
      }
    },
    computed: {
      ...mapGetters(['iOrgsysnum','userID'])
    },
    created() {
      this.fetchOrgList()
      this.getOrglistsq()
    },
    mounted() {
    },
    methods: {
      /* changecheck(val) {
          if (this.addListForm.iOrgsysnum instanceof Array) {
            this.addListForm.iOrgsysnum = this.addListForm.iOrgsysnum
              .splice(-1)
              .toString()
            console.log(this.addListForm.iOrgsysnum)
          }
          this.getAllDeviceList()
        },*/

      devicechange(val) {
        this.iDevicesysnumArr = val
      },
      devicefocus() {
        if (this.addListForm.iOrgsysnum.length > 0) {
          if (this.addListForm.iOrgsysnum instanceof Array) {
            this.addListForm.iOrgsysnum = this.addListForm.iOrgsysnum.splice(-1)[0]
            console.log(this.addListForm.iOrgsysnum)
            this.getAllDeviceList()
          }
        } else {
          this.$message({
            message: '请先选择机构',
            type: 'warning'
          })
        }
      },
      getAllDeviceList() {
        const ids = []
        this.addListForm.iDevicesysnumArr.map(item => {
          ids.push(item.iDevicesysnum)
        })
        // this.iDevicesysnumArr = ids
        getDevice({ iOrgsysnum: this.addListForm.iOrgsysnum, iDevicesysnumArr: ids }).then(res => {
          this.optionss = res.deviceList
        })
      },
      // 去除相同数据方法
      /* uniqueArr(materialData, addTableData) {
          let arr = addTableData.filter(item => {
            let str = JSON.stringify(item)
            return materialData.every(item => JSON.stringify(item) != str)
          })
          this.addTableData = arr
          //console.log(this.addTableData)
        },*/
      // this.uniqueArr(materialData,addTableData)
      // 获取节目单列表
      fetchOrgList() {
        // 获取机构数据
        getOrglist().then(res => {
          /* this.options = res.yhlist*/
          this.options = res.data
        })
        // 获取素材类型
        getSysType({ typeInfo: [3, 4, 7] }).then(res => {
          this.optionType = res.data[4]
          /* this.optionTag = res.syslist[3]*/ // 没有加code码之前
          this.optionTag = res.data[3]
          this.iDevTypes = res.data[7]
        })
      },
      // 获取所属机构有权限
      getOrglistsq() {
        getOrglists({ iOrgnum: this.iOrgnum }).then(res => {
          // console.log(res)
          this.optionslist.push(res.data)
          // this.optionslist = res.data
        })
      },
      // 添加节目单中添加素材按钮
      addMaterial(row, index) {
        this.addForm.strMaterialdetail = ''
        this.dialogVisible = true

        this.addTableData.forEach((i, index) => {
          this.$nextTick(() => {
            this.$refs.multipleaddTable.toggleRowSelection(i, false)
          })
        })

        /* this.materialData = this.multipleSelection
            this.addTableData = this.addTableData*/
        /* this.uniqueArr(this.materialData, this.addTableData)*/
      },
      handleSelectionChange(val) {
        // console.log(val)
        this.addListForm.materialList = val
        // this.addListForm.valArr = val
        // let list = JSON.stringify(val)
        /* val.forEach((val, index) => {
            this.materialData.forEach((v, i) => {
              // id 是每一行的数据id
              if (val.id == v.id) {
                //console.log(i)
              }
              let yi = i
              console.log(yi)
            })
          })*/
      },
      // 新增节目单
      publishPrograms(formName) {
        // console.log('>>>>>>>', this.addListForm)
        this.$refs[formName].validate(valid => {
          if (valid) {
            const arr = []
            this.strCycle.map(item => {
              item.map(value => {
                arr.push(value)
              })
            })

            this.addProgramswar([...new Set(arr)])
            // alert('submit!');
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      addProgramswar(arr, sDate1, sDate2) {
        if (this.addListForm.iOrgsysnum instanceof Array) {
          this.addListForm.iOrgsysnum = this.addListForm.iOrgsysnum
            .splice(-1)
            .toString()
        }

        // 判断所选日期是否与所选星期是否匹配
        const weeks = this.addListForm.strCycle
        let timestr1 = this.addListForm.strStartdate
        let timestr2 = this.addListForm.strEnddate

        let getWeek_index1 = (new Date(timestr1)).getDay()
        let getWeek_index2 = (new Date(timestr2)).getDay()
        const weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

        let dateSpan, iDays
        sDate1 = Date.parse(timestr1)
        sDate2 = Date.parse(timestr2)
        dateSpan = sDate2 - sDate1
        dateSpan = Math.abs(dateSpan)
        iDays = Math.floor(dateSpan / (24 * 3600 * 1000)) + 1

        let judgeValue = false
        if (iDays < 7) {
          let selectList = weekArr.slice(getWeek_index1, getWeek_index2 + 1)
          weeks.map((item, index) => {
            if (selectList.indexOf(item) == -1) {
              judgeValue = true
              return
            }
          })
        }
        if (judgeValue) {
          this.$message({
            message: '请选择' + weekArr[getWeek_index1] + '到' + weekArr[getWeek_index2],
            type: 'warning'
          })
          return
        }
        // 判断节目单素材管理表格提交没有数据的时候直接提交，有数据的时候提示必填后提交
        if (this.materialData.length > 0) {
          let isFlase = false
          const showarr = []
          this.materialData.forEach((item, index) => {
            showarr.push(item.iOrder)
            const s = showarr.join(',')
            if (item.iPlaytime === '' || item.iOrder === '' || s.replace(showarr[index], '').indexOf(showarr[index]) > -1) {
              isFlase = true
            } else {
              isFlase = false
            }
          })

          if (isFlase === false) {
            this.addListForm.materialList = JSON.stringify(this.addListForm.materialList)
            addPrograms(this.addListForm).then(res => {
              this.addListForm.strCycle = arr
              this.$router.push({ path: '/programme/index' })
            })
          } else {
            this.$message({
              message: '排序或播放次数不能为空或排序不可相同',
              type: 'warning'
            })
          }

          /* if (this.addListForm.materialList.length <= 0) {
              this.showspan = true
              //console.log('请勾选后提交')
              // return false
            } else {
              let isFlase = false
              let showarr = []
              this.addListForm.materialList.forEach((item, index) => {
                showarr.push(item.iOrder)
                let s = showarr.join(',')
                if (item.iPlaytime === '' || item.iOrder === '' || s.replace(showarr[index], '').indexOf(showarr[index]) > -1) {
                  isFlase = true
                } else {
                  isFlase = false
                }
              })
              if (isFlase == false) {
                this.addListForm.materialList = JSON.stringify(this.addListForm.materialList)
                addPrograms(this.addListForm).then(res => {
                  this.addListForm.strCycle = arr
                  this.$router.push({ path: '/programme/index' })
                })
              } else {
                this.$message({
                  message: '排序或播放次数不能为空或排序不可相同',
                  type: 'warning'
                })
              }
            }*/
        } else {
          this.addListForm.materialList = JSON.stringify(this.addListForm.materialList)
          addPrograms(this.addListForm).then(res => {
            this.addListForm.strCycle = arr
            // this.addListForm.materialList = this.materialData
            // console.log(res)
            this.$router.push({ path: '/programme/index' })
          })
        }
      },
      // 新增页面弹窗中搜索
      addsearch(param) {
        // debugger
        // if (this.addForm.iOrgsysnum instanceof Array) {
        //   console.log('打印出来》》。',this.addForm.iOrgsysnum,)
        //   this.addForm.iOrgsysnum = this.addForm.iOrgsysnum.splice(-1)[0]
        //   console.log('打印出来',this.addForm.iOrgsysnum)
        // }
        const submitData = JSON.parse(JSON.stringify(this.addForm))

        if (submitData.iOrgsysnum.length > 0) {
          submitData.iOrgsysnum = submitData.iOrgsysnum.splice(-1).join(',')
          addsearchPrograms(submitData).then(res => {
            // this.uniqueArr(this.materialData, this.addTableData)
            this.addTableData = res.result
            /* this.uniqueArr(this.materialData, this.addTableData)*/
            // console.log(this.addTableData)
          })
        }
      },

      // 点击新增素材弹窗中复选框
      changeFun(val) {
        this.multipleSelection = val
        // console.log(val)
      },

      // 点击新增素材弹窗确认按钮
      addsearchture() {
        this.materialData = this.materialData.concat(this.multipleSelection)
        this.addTableData.forEach((item, index) => {
          this.addTableData[index].iPlaytime = ''
          this.addTableData[index].iOrder = ''
        })
        // console.log(this.materialData)
        this.materialData.forEach((i, index) => {
          this.$nextTick(() => {
            this.$refs.multipleTable.toggleRowSelection(i, true)
          })
        })
      },

      /* toggleSelection(rows) {
          if (rows) {
            rows.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row);
            });
          } else {
            this.$refs.multipleTable.clearSelection();
          }
        },*/

      // 移除当前行数据
      deleteRow(index, rows) {
        this.showspan = false
        rows.splice(index, 1)
        /* this.uniqueArr(this.materialData, this.addTableData)*/
      },

      // 获取周期checkbox
      checkinlist() {
        // this.$router.push({ path: '/programme/editProgramme', query: { weekAll:this.addListForm.strCycle} })
        // const weeks = this.addListForm.strCycle

      },

      // 点击新增素材弹窗中 <取消按钮> 方法(关闭弹窗)
      clearsearch() {
        this.dialogVisible = false
      }
    }
  }
</script>
<style type="scss" scoped>
  .searbtn {
    margin-left: -60px;
  }

  .showspan {
    color: red;
    font-size: 12px;
  }

  .timespan {
    color: red;
    font-size: 12px;
  }

  .el-form-itemc {
    position: relative;
    top: 5px;
    margin-left: -90px;
    width: 185px;
  }
</style>
<style>
  .el-image-viewer__close {
    color: #fff;
  }
</style>
